import {AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild, ViewContainerRef} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {NzMessageService} from "ng-zorro-antd";
import {FetchService} from "../../../core/net/fetch.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {endOfMonth, format, startOfMonth, addDays} from "date-fns";
import {UnifiedMap, UnifiedMapComponent, UnifiedMapMode, ViewRange} from "unified-map";
import {Observable, Subject} from "rxjs";
import {MapUiService} from "../../one-map/map-ui.service";
import {HttpClient} from "@angular/common/http";
import {map} from "rxjs/operators";

@Component({
  selector: 'app-dispatch-gysh',
  templateUrl: './dispatch-gysh.component.html',
  styleUrls: ['../dispatch-common.scss', './dispatch-gysh.component.scss']
})
export class DispatchGyshComponent implements OnInit, AfterViewInit, OnDestroy {
  areaData = [
    {name: '宁东供水', value: 0, code: 'ndgs'},
    {name: '中南部供水', value: '4', code: 'znbgs'},
    {name: '西线供水', value: 1, code: 'xxgs'},
    {name: '东线供水', value: '3'},
    {name: '盐同红', value: '5'},
    {name: '清水河', value: '6'},
    {name: '卫宁供水', value: '7'},
  ];

  rightTableData;
  processOpt: any = {
    grid: {
      top: 50,
      bottom: 60,
      left: 50,
      right: 50
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        animation: false,
        label: {
          backgroundColor: '#505765'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        name: 'm³',
        type: 'value'
      }
    ],
    series: [
      {
        name: '用水量',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '累计用水量',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  };
  processOptChange: any = {};
  searchForm: FormGroup;
  rangePickerValue = [addDays(new Date(), -15), new Date()];

  // map
  @ViewChild("map", {static: true}) unifiedMap: UnifiedMapComponent;
  mapInstance: UnifiedMap;
  viewRange: ViewRange = [[106.31, 38.06], [106.77, 38.41]];
  viewRangeMap = {
    xxgs: [[105, 37.67], [107.26, 39.25]],
    ndgs: [[106.31, 38.06], [106.77, 38.41]],
    znbgs: [[105.6, 35.3], [106.95, 36.21]],
  };
  geoserverUrl = (window as any).environment.geoserverUrl;
  chartTitle = '用水过程线';
  selecteRow: any = {};
  selectArea: any =  {name: '宁东供水', value: 0, code: 'ndgs'};

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private mapUiService: MapUiService,
    private http: HttpClient,
    private elementRef: ElementRef,
    private router: Router
  ) {
    this.searchForm = this.fb.group({
      key: ['']
    });
  }

  ngOnInit(): void {
    this.areaClick(this.selectArea);
  }

  ngAfterViewInit(): void {

  }

  ngOnDestroy(): void {
    this.clearOverlay();
  }

  clearOverlay() {
    this.mapUiService.olMap.getOverlays().clear();
  }

  initMap() {
    this.mapUiService.getMapInstance().then((mapInstance) => {
      this.mapInstance = mapInstance;
      this.mapUiService.hideAllLayer();

      this.addMonitorPoint({
        layerName: `gydd-${this.selectArea.code}`,
        url: `${this.geoserverUrl}nxszy/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=nxszy%3Agydd-${this.selectArea.code}&maxFeatures=20000&outputFormat=application%2Fjson`
      });

      this.mapUiService.addVectorLayer({
        type: "polyline",
        layerName: `gydd-${this.selectArea.code}-line`,
        style: {
          fill: "#ff1343",
          fillOpacity: 1,
          outline: "#ff1343",
          outlineWidth: 1,
          lineWidth: 3
        },
        visible: true
      });

      this.mapUiService.addVectorLayer({
        type: "polygon",
        layerName: `gydd-${this.selectArea.code}-polygon`,
        style: {
          fill: "#5BB6C9",
          fillOpacity: 0.7,
          outline: "#a3e4ff",
          outlineWidth: 1,
          lineWidth: 3
        },

        visible: true,
        zIndex: 2
      });

      this.viewRange = this.viewRangeMap[this.selectArea.code];
      this.mapInstance
        .flyTo(this.viewRange, {duration: 1000})
        .then((r) => {
          // console.log('flyToPoint end');
        });
    });
  }

  addMonitorPoint(opt) {
    const mapInstance = this.mapInstance;
    this.fetchJson(opt.url).subscribe((features) => {
      if (!mapInstance.hasVectorLayer(opt.layerName)) {
        mapInstance.addVectorLayer(opt.layerName, {
          zIndex: opt.zIndex || 5
        });
      } else {
        mapInstance.removeEntitiesFromLayer(opt.layerName);
      }

      // 1-泵站 2-水库 3-工业单位 4-水厂 5-水源地
      const iconMap = [
        '',
        `./assets/images/display/icon-pump.png`,
        `./assets/images/display/icon-reservoir.png`,
        `./assets/images/display/icon-qy.png`,
        `./assets/images/display/icon-shuichang.png`,
        `./assets/images/display/icon-shuichang.png`,
      ];

      features.map((feature) => {
        mapInstance.addPointEntity(opt.layerName, {
          id: feature.id,
          coordinates: [feature.geometry.coordinates],
          properties: {...feature.properties, type: 'point'},
          style: {
            icon: iconMap[feature.properties.type],
            scale: 1
          },
        }, {
          text: feature.properties.Name,
          weight: "bold",
          size: 13,
          fill: "#ffffff",
          outline: "#043f69",
          outlineWidth: 2,
          pixelOffset: [0, 12]
        });
      });

      mapInstance.updateVectorLayer(opt.layerName, {
        visible: true
      });
    });
  }

  fetchJson(url): Observable<any> {
    return this.http.get(url).pipe(map(result => {
      return result["features"];
    }));
  }

  mapInitialized(initMode: UnifiedMapMode): void {
  }

  entityClick(event: any): void {
  }

  entityHovered(event: any): void {
  }

  getTableData(): void {
    // 生活用水
    this.fetchService.post('intake/wrsWiuMp/listByType',  {nt: this.selectArea.code} ).subscribe(res => {
      this.rightTableData = res;
      this.rowClick(res[0]);
    });
  }

  rowClick(row): void {
    this.selecteRow = row;
    this.chartTitle = row.mp_nm + '用水过程线';
    this.queryProcessList();
  }

  areaClick(area): void {
    this.selectArea = area;
    this.initMap();
    this.getTableData();
  }

  queryProcessList() {
    const url = 'intake/wrsWiuMp/query';
    const params = {
      mpCd: this.selecteRow.mp_cd,
      beginTime: format(this.rangePickerValue[0], 'YYYY-MM-DD'),
      endTime: format(this.rangePickerValue[1], 'YYYY-MM-DD'),
    };
    this.fetchService.post<any>(url, params).subscribe(res => {
      const originalDataList = res;
      const xAxisData = this.getItemValues(originalDataList, 'dt').map(item => {
        return format(new Date(item), 'MM-DD');
      });
      console.log(xAxisData);
      const commonOpt = {
        legend: {
          data: ['补水量', '累计补水量'],
          bottom: 10
        },
        xAxis: {
          data: xAxisData
        }
      };
      this.processOptChange = {
        ...commonOpt, ...{
          series: [
            {
              name: '日取水量',
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#289df5', // 折线条的颜色
                  borderColor: '#289df5', // 拐点边框颜色
                  areaStyle: {
                    type: 'default',
                    opacity: 0.1
                  }
                }
              },
              data: this.getItemValues(originalDataList, 'dayW')
            }
          ]
        }
      };
    });
  }

  private getItemValues(list, key) {
    return list.map(i => {
      return i[key] || 0;
    });
  }

  rangePickerValueChange(e): void {
    this.queryProcessList();
  }

  goPage(pageName): void {
    this.router.navigate([`/realtime-control/dispatch-${pageName}`]);
  }

}
